<template>
  <div class="flex flex-col gap-4">
    <div class="flex items-center gap-2">
      <router-link to="/sentences">
        <Button variant="ghost" size="sm">
          <ArrowLeft class="mr-2 h-4 w-4" />
          返回例句列表
        </Button>
      </router-link>
      <h1 class="text-3xl font-bold tracking-tight">添加新例句</h1>
    </div>

    <Card>
      <form @submit.prevent="handleSubmit">
        <CardHeader>
          <CardTitle>例句信息</CardTitle>
          <CardDescription>输入新示例句子的详细信息。</CardDescription>
        </CardHeader>
        <CardContent class="space-y-4">
          <div class="space-y-2">
            <Label for="sentence">例句</Label>
            <Textarea
                id="sentence"
                placeholder="输入一个示例句子"
                :rows="3"
                v-model="sentence"
                required
            />
          </div>

          <div class="space-y-2">
            <Label for="context">上下文（可选）</Label>
            <Textarea
                id="context"
                placeholder="输入关于此句子的上下文或附加信息"
                :rows="2"
                v-model="context"
            />
          </div>

          <div class="space-y-2">
            <Label>相关单词</Label>
            <div class="flex gap-2">
              <Input
                  placeholder="添加相关单词ID"
                  v-model="relatedWordId"
                  @keydown.enter.prevent="handleAddRelatedWord"
              />
              <Button type="button" @click="handleAddRelatedWord">
                添加
              </Button>
            </div>
            <div class="flex flex-wrap gap-2 mt-2">
              <Badge
                  v-for="word in relatedWords"
                  :key="word.id"
                  variant="secondary"
                  class="flex items-center gap-1"
              >
                {{ word.word }} (ID: {{ word.id }})
                <X
                    class="h-3 w-3 cursor-pointer"
                    @click="handleRemoveRelatedWord(word.id)"
                />
              </Badge>
            </div>
          </div>
        </CardContent>
        <CardFooter class="flex justify-between">
          <Button variant="outline" type="button" @click="router.back()" :disabled="isLoading">
            取消
          </Button>
          <Button type="submit" :disabled="isLoading">
            <Loader2 v-if="isLoading" class="mr-2 h-4 w-4 animate-spin" />
            {{ isLoading ? "添加中..." : "添加例句" }}
          </Button>
        </CardFooter>
      </form>
    </Card>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '@/components/ui/toast'
import { ArrowLeft, X, Loader2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'

// 导入API模块
import sentenceAPI from '@/api/sentence.js'
import wordAPI from '@/api/word.js'

const router = useRouter()
const { toast } = useToast()

const sentence = ref('')
const context = ref('')
const relatedWordId = ref('')
const relatedWords = ref([])
const isLoading = ref(false)


// 获取相关单词的详细信息
const fetchWordInfo = async (wordId) => {
  try {
    const response = await wordAPI.getWord(wordId)
    if (response.code === 200) {
      return response.data
    } else {
      throw new Error(response.message || '获取单词信息失败')
    }
  } catch (error) {
    console.error('获取单词信息失败:', error)
    throw error
  }
}

const handleAddRelatedWord = async () => {
  const wordId = relatedWordId.value.trim()

  if (!wordId) {
    toast({
      title: "输入错误",
      description: "请输入单词ID",
      variant: "destructive",
    })
    return
  }

  // 检查是否已添加
  if (relatedWords.value.some(word => word.id === parseInt(wordId))) {
    toast({
      title: "重复添加",
      description: "该单词已添加",
      variant: "destructive",
    })
    relatedWordId.value = ''
    return
  }

  try {
    const wordInfo = await fetchWordInfo(wordId)
    relatedWords.value.push({
      id: wordInfo.id,
      word: wordInfo.word
    })
    relatedWordId.value = ''
  } catch (error) {
    toast({
      title: "添加失败",
      description: error.message || "无法获取单词信息",
      variant: "destructive",
    })
  }
}

const handleRemoveRelatedWord = (wordId) => {
  relatedWords.value = relatedWords.value.filter(w => w.id !== wordId)
}

const handleSubmit = async () => {
  // 验证
  if (!sentence.value.trim()) {
    toast({
      title: "错误",
      description: "例句是必填项",
      variant: "destructive",
    })
    return
  }

  isLoading.value = true

  try {
    // 准备提交数据
    const sentenceData = {
      sentence: sentence.value.trim(),
      context: context.value.trim() || undefined,
      wordIds: relatedWords.value.map(word => word.id)
    }

    // 调用API创建例句
    const response = await sentenceAPI.createSentence(sentenceData)

    if (response.code === 200) {
      toast({
        title: "例句已添加",
        description: "例句已成功添加。",
      })

      // 重置表单
      sentence.value = ''
      context.value = ''
      relatedWords.value = []
    } else {
      throw new Error(response.message || '添加例句失败')
    }
  } catch (error) {
    console.error('添加例句失败:', error)
    toast({
      title: "添加失败",
      description: error.message || "添加例句时发生错误",
      variant: "destructive",
    })
  } finally {
    isLoading.value = false
  }
}
onMounted(() => {
   fetchsentences()
})
</script>
